<template>
  <div class="search-wrap">
   <input type="text"
   placeholder="请输入城市名称"
   class="search-input"
   v-model="keywords">
  <div class="search-content"
  v-show="keywords"
  ref='searchcontent'>
    <ul>
      <li
      v-for="(list,index) in searchRes"
      :key='index'
       @click="cityClick(list)"
      class="search-list">{{list.name}}</li>
      <li class="search-list"
       style="text-align: center;"
      v-show="searchRes.length==0">没有匹配</li>
    </ul>
  </div>
  </div>
</template>

<script>
  import BScroll from 'better-scroll'
  import {mapState,mapMutations} from 'vuex'
  export default{
    name:'CitySearch',
    props:['cities'],
    data (){
      return {
        keywords:'',
        searchRes:[],
        timer:null
      }
    },

    mounted (){
        this.scroll = new BScroll(this.$refs.searchcontent,{
          click:true,
          tap:true
        });
    },

      methods:{
        ...mapMutations({
          changeCity:'changeCity'
        }),
     cityClick(obj){
       this.changeCity(obj.name);
       this.$router.push({
         path:'/'
       })
     }
    },
    watch:{
      keywords (){
        // 定时器模拟获取数据延时
        let _this=this;
        if(_this.timer){
          clearTimeout(_this.timers);
        }
        if(!_this.keywords){
          _this.searchRes=[];
          return;
        }
        _this.timer=setTimeout(function(){

          let result=[];
          for(let i in _this.cities){
          _this.cities[i].forEach((item)=>{
            // item.spell
            // item.name
            // keywords
            if(item.spell.indexOf(_this.keywords)>-1||item.name.indexOf(_this.keywords)>-1){
              result.push(item)
            }
          })
          }
          _this.searchRes=result;
        },100);

      }
    }
  }
</script>

<style scoped="scoped">
  .search-wrap{
    height:0.7rem;
    background-color: rgb(0,188,212);
   padding: 0.1rem;
  }
  .search-input{
    border-radius: 0.1rem;
    width: 100%;
    height: 100%;
    text-align: center;
    padding: 0rem 0.1rem;
    box-sizing: border-box;
  }
  .search-content{
    overflow: hidden;
    background-color: #eee;
    position: absolute;
    left: 0;
    top: 1.75rem;
    right: 0;
    bottom: 0;
    z-index: 999;
  }
  .search-list{
    height: 0.75rem;
    line-height: 0.75rem;
    padding-left: 0.2rem;
    border-bottom: 1px solid #eee;
    background: #fff;
  }
</style>
